const { Op, where } = require("sequelize");
const sequelize = require("../../model/index")

const AppError = require("../../utils/appError")
const userGroupMessage = require("../../model/userGroupMessage");
const userGroup = require("../../model/userGroup");
const groupMessage = require("../../model/groupMessage");
const UserInfo = require("../../model/userinfo")
const { getUuid } = require("../../utils/index")

const ServerAddGroupMessage = async ({ groupId, messageContent, messageUserId, messageType, messageSendType, messageStatus }) => {
  const res = await groupMessage.create({ groupId, messageContent, messageUserId, messageType, messageSendType, messageStatus });
  if (res) {
    return {
      isok: 1,
      message: "创建成功",
      data: res
    }
  } else {
    return {
      isok: 0,
      message: "创建失败",
      data: false
    }
  }
}
const ServerGetGroupMessageById = async (messageid) => {
  const GetGroupMessageres = await groupMessage.findOne({
    where: {
      id: messageid
    }
  }, { raw: true })
  if (GetGroupMessageres) {
    return {
      isok: true,
      message: "查询成功",
      data: GetGroupMessageres
    }
  }
  return {
    isok: false,
    message: "查询失败",
    data: {}
  }
}
const ServerGetGroupMessageByIdList = async (messageIdlist) => {
  const GetGroupMessageres = await groupMessage.findAll({
    where: {
      id: {
        [Op.in]: messageIdlist
      }
    }
  }, { raw: true })
  if (GetGroupMessageres) {
    return {
      isok: true,
      message: "查询成功",
      data: GetGroupMessageres
    }
  }
  return {
    isok: false,
    message: "查询失败",
    data: {}
  }
}
module.exports = {
  ServerGetGroupMessageList: async (userId) => {
    try {
      const GroupMessageres = await userGroupMessage.findAll({
        where: {
          userId,
          isShowGroupMessage: true
        }
      }, { raw: true })
      if (GroupMessageres.length) {
        const groupIdlist = GroupMessageres.map(item => item.groupId);
        const messageList = await ServerGetGroupMessageByIdList(GroupMessageres.map(item => item.messageLastdate))
        const userGroupres = await userGroup.findAll({
          where: {
            id: {
              [Op.in]: groupIdlist
            }
          }
        }, { raw: true })
        if (userGroupres.length) {
          return {
            isok: 1,
            message: "查询成功",
            data: userGroupres.map(item => {
              const user = GroupMessageres.find(data => data.groupId == item.id)
              return {
                id: user.groupId,
                name: user.groupName ? user.groupName : item.groupName,
                avatar: item.groupAvatar,
                message: messageList.data.find(data => item.id == data.groupId)['messageContent'],
                messageType: messageList.data.find(data => item.id == data.groupId)['messageType'],
                noMessageNum: user.noMessageNum,
                lastMessageTime: messageList.data.find(data => item.id == data.groupId)['createdAt'],
                type: "group"
              }
            })
          }
        }
        return {
          isok: 1,
          message: "暂无数据",
          data: []
        }
      }
      return {
        isok: 1,
        message: "暂无数据",
        data: []
      }
    } catch (error) {
      console.log(error);
      return {
        isok: 0,
        message: "查询失败",
        data: []
      }
    }
  },
  ServerCreateGroup: async (groupCreatorId, userName, userIdList) => {
    const t = await sequelize.transaction();
    try {
      const groupRoom = getUuid()
      const createGroupres = await userGroup.create({
        groupCreatorId,
        groupRoom,
        groupName: userName + "创建的群聊",
        groupAvatar: "http://imgfile.xxkdjy.top/2024013116291818691.jpg",
        groupNumber: userIdList.length,
        userIdList: userIdList.length ? userIdList.join(",") : ""
      }, { transaction: t });
      if (createGroupres.dataValues) {
        const AddGroupMessageres = await ServerAddGroupMessage({
          groupId: createGroupres.dataValues.id,
          messageContent: userName + ' 已经创建群聊快来聊天吧',
          messageType: "data",
          messageSendType: 0
        }, { transaction: t })
        if (AddGroupMessageres.isok) {
          const userGrouplist = userIdList.map(item => {
            return {
              userId: item,
              groupId: createGroupres.dataValues.id,
              groupName: '',
              messageLastdate: AddGroupMessageres.data.id,
              noMessageNum: 1
            }
          });
          const userGroupMessageres = await userGroupMessage.bulkCreate(userGrouplist, { transaction: t });
          if (userGroupMessageres.length) {
            await t.commit();
            return {
              isok: 1,
              message: "创建成功",
              data: createGroupres,
              userGroupMessagelist: userGroupMessageres
            }
          } else {
            await t.rollback();
            return {
              isok: 0,
              message: "创建失败",
              data: false
            }
          }
        } else {
          await t.rollback();
          return {
            isok: 0,
            message: "创建失败",
            data: false
          }
        }
      }
      await t.rollback();
      return {
        isok: 0,
        message: "创建失败",
        data: false
      }
    } catch (error) {
      console.log(error);
      await t.rollback();
      return {
        isok: 0,
        message: "创建失败",
        data: false
      }
    }
  },
  ServerGetGroupInfoById: async (groupId, userId) => {
    const GroupMessageres = await userGroupMessage.findOne({
      where: {
        [Op.and]: {
          userId,
          groupId
        }
      }
    }, { raw: true });
    if (GroupMessageres) {
      const [groupUserList, GroupInfores] = await Promise.all([
        userGroupMessage.findAll({
          where: {
            groupId: GroupMessageres.groupId
          }
        }, { raw: true }),
        userGroup.findOne({
          where: {
            id: GroupMessageres.groupId
          }
        }, { raw: true })],
      )
      if (!GroupInfores) {
        return {
          isok: 0,
          message: "暂无群聊",
          data: false
        }
      }
      const userIdList = groupUserList?.map(item => {
        return {
          id: item.userId,
          commendName: item.userCommendName
        }
      })
      const userinfolist = await UserInfo.findAll({
        where: {
          id: {
            [Op.in]: userIdList.map(item => item.id)
          }
        }
      }, { raw: true })
      const userList = userinfolist.map(item => {
        const commendName = userIdList.find(data => data.id == item.id)['commendName']
        return {
          id: item.id,
          name: commendName ? commendName : item.userName,
          avatar: item.userAvatar
        }
      })
      const groupInfo = {
        id: GroupInfores.id,
        avatar: GroupInfores.groupAvatar,
        creatorId: GroupInfores.groupCreatorId,
        name: GroupInfores.groupName,
        number: GroupInfores.groupNumber
      }
      return {
        isok: 1,
        message: "获取成功",
        data: {
          userList,
          groupInfo,
          userCommendName: GroupMessageres.userCommendName,
          usergroupName: GroupMessageres.groupName
        }
      }
    }
    return {
      isok: 0,
      message: "获取失败",
      data: false
    }
  },
  ServerGetGroupMessage: async ({ pageSize, startId, messageId }) => {
    const groupres = await userGroup.findOne({
      where: {
        id: messageId
      }
    }, { raw: true })
    if (groupres) {
      let countt;
      let messagelist;
      if (startId) {
        const { count, rows } = await groupMessage.findAndCountAll({
          where: {
            groupId: groupres.id,
            messageStatus: 1,
            id: {
              [Op.lt]: startId,
            }
          },
          limit: pageSize,
          order: [
            ['createdAt', 'DESC']
          ],
        }, { raw: true });
        countt = rows.length;
        messagelist = rows
      } else {
        const { count, rows } = await groupMessage.findAndCountAll({
          where: {
            groupId: groupres.id,
            messageStatus: 1,
          },
          limit: pageSize,
          order: [
            ['createdAt', 'DESC']
          ],
        }, { raw: true });
        countt = rows.length;
        messagelist = rows
      }

      const usersendmessage = messagelist.filter(item => item.messageSendType);
      const systemsendmessage = messagelist.filter(item => !item.messageSendType)
      const [userInfoList, userGroups] = await Promise.all([
        UserInfo.findAll({
          where: {
            id: usersendmessage.map(item => item.messageUserId),
          }
        }, { raw: true }),
        userGroupMessage.findAll({
          where: {
            [Op.and]: {
              userId: {
                [Op.in]: usersendmessage.map(item => item.messageUserId)
              },
              groupId: messageId
            }
          }
        }, { raw: true })
      ])
      const messageinfolist = usersendmessage.map((item) => {
        const userGroupData = userGroups.map(item => item.dataValues).find(data => data.userId == item.messageUserId);
        const commendName = userGroupData ? userGroupData.userCommendName : null;
        const userInfo = userInfoList.find(data => data.id == item.messageUserId);
        const avatar = userInfo ? userInfo.userAvatar : '';
        const userName = userInfo ? userInfo.userName : '未知用户';
        return {
          id: item.messageUserId,
          messageId: item.id,
          messagetype: item.messageType,
          content: item.messageContent,
          avatar: avatar,
          name: commendName ? commendName : userName,
          messageSendType: item.messageSendType,
          messageStatus: item.messageStatus,
          createdAt: item.createdAt
        }
      })
      if (countt) {
        return {
          isok: true,
          message: "获取成功",
          data: {
            total: countt,
            list: [...messageinfolist, ...systemsendmessage.map(data => {
              return {
                messageId: data.id,
                content: data.messageContent,
                messageSendType: data.messageSendType,
                createdAt: data.createdAt
              }
            })].sort((a, b) => {
              return new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime()
            })
          }
        }
      }
      return {
        isok: 1,
        message: "查询失败",
        data: {
          total: 0,
          list: []
        }
      }
    }
    return {
      isok: 0,
      message: "查询失败",
      data: false
    }
  },
  ServerChangeCommendName: async ({ type, userId, groupId, groupName, userCommendName }) => {
    if (type == 'groupName' && groupName) {
      await userGroupMessage.update({ groupName }, {
        where: {
          userId,
          groupId
        }
      })
    } else {
      await userGroupMessage.update({ userCommendName }, {
        where: {
          userId,
          groupId
        }
      })
    }
    return {
      isok: 1,
      message: "修改成功",
      data: true
    }
  },
  ServerUnentryUser: async ({ userId, groupId }) => {
    const groupinfo = await userGroup.findOne({
      where: {
        id: groupId
      }
    }, { raw: true })
    if (groupinfo) {
      if (groupinfo.groupCreatorId == userId) {
        userGroupMessage.destroy({
          where: {
            groupId: groupId
          }
        }, {
          raw: true
        })
        const res = await userGroup.destroy({
          where: {
            id: groupId
          }
        })

        if (res) {
          return {
            isok: 1,
            message: "成功",
            data: groupinfo.userIdList.split(","),
            type: 1
          }
        }
      } else {
        userGroupMessage.destroy({
          where: {
            userId: userId,
            groupId: groupId
          }
        }, {
          raw: true
        })
        const userlist = groupinfo.userIdList.split(",").filter(item => item !== userId);
        const groupNumber = groupinfo.groupNumber - 1;
        const res = await userGroup.update({
          groupNumber: groupNumber,
          userIdList: userlist.join(",")
        }, {
          where: {
            id: userId
          }
        })
        if (res) {
          return {
            isok: 1,
            message: "成功",
            data: true,
            type: 0
          }
        }
      }
    }
    return {
      isok: 0,
      message: "失败",
      data: false
    }
  },
  ServerUpdataGroupname: async ({ groupId, name }) => {
    const groupinfo = await userGroup.update({
      groupName: name
    }, {
      where: {
        id: groupId
      }
    })
    if (groupinfo) {
      return {
        isok: 1,
        message: "成功",
        data: true
      }
    }
    return {
      isok: 0,
      message: "失败",
      data: false
    }
  },
  ServerSendMessageToGroup: async ({ groupId, userId, content, messageType = "data", messageSendType = 1 }) => {
    const t = await sequelize.transaction();
    try {
      const MessageGroupUser = await userGroupMessage.findOne({
        where: {
          userId,
          groupId
        }
      }, { raw: true })
      if (MessageGroupUser) {
        const groupessage = await groupMessage.create({
          groupId,
          messageUserId: userId,
          messageType: messageType,
          messageContent: content,
          messageSendType: messageSendType
        }, { raw: true })
        const updataGroupmessage = await userGroupMessage.update({
          messageLastdate: groupessage.id,
          noMessageNum: MessageGroupUser.noMessageNum + 1
        }, {
          where: {
            userId,
            groupId
          }
        }, {})
        userGroupMessage.update({
          messageLastdate: groupessage.id,
        }, {
          where: {
            groupId
          }
        }, {})
        const userinfo = await UserInfo.findOne({
          where: {
            id: userId
          }
        }, { raw: true })
        const group = await userGroup.findOne({
          where: {
            id: MessageGroupUser.groupId
          }
        }, { raw: true })
        if (updataGroupmessage) {
          await t.commit();
          const messagedata = {}
          messagedata.avatar = userinfo.userAvatar;
          messagedata.content = content;
          messagedata.createdAt = groupessage.createdAt;
          messagedata.id = userId;
          messagedata.messageId = groupId;
          messagedata.messageSendType = messageSendType;
          messagedata.messageType = messageType;
          messagedata.name = MessageGroupUser.userCommendName ?? userinfo.userName;
          return {
            isok: 1,
            message: "发送成功",
            data: messagedata,
            group: group
          }
        } else {
          return {
            isok: 0,
            message: "",
            data: {}
          }
        }
      } else {
        return {
          isok: 0,
          data: false,
          message: "该群没有该用户"
        }
      }
    } catch (error) {
      await t.rollback();
      console.log(error);
      return {
        isok: 0,
        message: "出错了",
        data: false
      }
    }
  },
  ServerAddGroupMessage,
  ServerGetGroupMessageById
}